package com.mrzhou.auth.filter;

import com.mrzhou.auth.constant.AuthConstant;
import com.mrzhou.auth.support.IntegrationAuthenticationContext;
import com.mrzhou.auth.support.IntegrationAuthenticationEntity;
import com.mrzhou.auth.utils.TokenUtil;
import com.mrzhou.core.tool.api.R;
import com.mrzhou.core.tool.constants.StringSymbol;
import com.mrzhou.web.util.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;

/**
 *  通过过滤器处理客户端在认证失败后抛出的认证失败的json
 */
@Component
@Slf4j
public class IntegrationAuthenticationClientFilter extends OncePerRequestFilter {

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        if(!request.getRequestURI().equals("/oauth/token")){
            chain.doFilter(request, response);
            return;
        }

        String[] clientDetails = null;
        try {
            clientDetails = this.isHasClientDetails(request);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("客户端【{}】检验[Authorization]失败", WebUtil.getIp(request));
            WebUtil.writerError(R.fail(HttpStatus.UNAUTHORIZED.value(), "客户端信息检测失败！"), response, HttpStatus.UNAUTHORIZED.value());
            return;
        }

        if (clientDetails == null) {
            WebUtil.writerError(R.fail(HttpStatus.UNAUTHORIZED.value(), "请求中未包含客户端信息！"), response, HttpStatus.UNAUTHORIZED.value());
            return;
        }
        this.handler(request, response, chain, clientDetails);
    }

    private void handler(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain, String[] clientDetails) throws IOException, ServletException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication != null && authentication.isAuthenticated()) {
            filterChain.doFilter(request, response);
            return;
        }

        ClientDetails details = this.clientDetailsService.loadClientByClientId(clientDetails[0]);

        if(!details.getClientSecret().equalsIgnoreCase(AuthConstant.CLIENT_ENCRYPT + clientDetails[1])) {
            WebUtil.writerError(R.fail(HttpStatus.UNAUTHORIZED.value(), "客户端信息错误, 检查后重试！"), response, HttpStatus.UNAUTHORIZED.value());
            return ;
        }

        UsernamePasswordAuthenticationToken token =
                new UsernamePasswordAuthenticationToken(details.getClientId(), details.getClientSecret(), details.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(token);

        // 将client的信息保存到线程的上下文中, 减少数据的查询
        IntegrationAuthenticationEntity entity = IntegrationAuthenticationContext.get();
        entity.setClientId(details.getClientId());
        IntegrationAuthenticationContext.set(entity); // 将客户端的信息保存到当前线程的上下文中
        filterChain.doFilter(request,response);
    }

    // 判断请求中是否包含client信息, 不包含返回false
    private String[] isHasClientDetails(HttpServletRequest request) {
        String[] params = null;

        String header = request.getHeader(HttpHeaders.AUTHORIZATION);

        if(header != null) {
            String basic = header.substring(0, TokenUtil.HEADER_PREFIX.length());

            if (basic.contains(TokenUtil.HEADER_PREFIX)) {
                String tmp = header.substring(TokenUtil.HEADER_PREFIX.length());
                String defaultClientDetails = new String(Base64.getDecoder().decode(tmp));

                String[] clientArrays = defaultClientDetails.split(StringSymbol.COLON);

                if (clientArrays.length != 2) {
                    return params;
                } else {
                    params = clientArrays;
                }
            }
        }
        String id = request.getParameter(TokenUtil.CLIENT_ID);
        String secret = request.getParameter(TokenUtil.CLIENT_SECRET);

        if (header == null && id != null) {
            params = new String[]{id, secret};
        }

        return params;
    }

}
